using System;
using System.Drawing.Design;
using System.ComponentModel.Design;
using DMTT.Workflow.Activities;
using System.ComponentModel;
using System.Workflow.ComponentModel;

namespace DMTT.Workflow.Activities.Design
{
    public class MappingEditor : UITypeEditor
	{
        public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (context.Instance == null)
                throw new ArgumentException("Can't get component instance!");
            IMapProperties mapper = context.Instance as IMapProperties;
            if (mapper == null)
                throw new ArgumentException("Can't get instance of type IMapProperties!");
            if (mapper.SourceType == null)
                throw new ArgumentException("No source type found!");
            if (mapper.DestinationType == null)
                throw new ArgumentException("No destination type found!");

            MappingForm form = new MappingForm(mapper);
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                MappingCollection mapCol = form.GetMappings();
                
                PropertyDescriptorCollection props = TypeDescriptor.GetProperties(context.Instance);
                foreach (PropertyDescriptor prop in props)
                {
                    if (prop.Name == "Mappings")
                    {
                        IDesignerHost host = ((Activity)context.Instance).Site.GetService(typeof(IDesignerHost)) as IDesignerHost;
                        if (host != null)
                        {
                            IComponentChangeService ccs = host.GetService(typeof(IComponentChangeService)) as IComponentChangeService;
                            if (ccs != null)
                            {
                                ccs.OnComponentChanging(context.Instance, prop);
                                mapper.Mappings = mapCol;
                                ccs.OnComponentChanged(context.Instance, prop, null, mapCol);
                            }
                        }
                    }
                }
                return mapCol;
            }
            return mapper.Mappings;
        }

        public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }
    }
}
